package com.szsky.sky.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szsky.sky.dto.AttendanceStatisticsDto;
import com.szsky.sky.dto.AttendanceStatisticsQuery;
import com.szsky.sky.dto.BasicPersonnelInformationDto;
import com.szsky.sky.dto.mq.Character;
import com.szsky.sky.dto.mq.ToZeroProducerDto;
import com.szsky.sky.entity.*;
import com.szsky.sky.entity.oa.GorgUser;
import com.szsky.sky.entity.portal.AppMUser;
import com.szsky.sky.mapper.*;
import com.szsky.sky.mapper.oa.GorgUserMapper;
import com.szsky.sky.mapper.portal.AppMUserMapper;
import com.szsky.sky.pojo.Employee;
import com.szsky.sky.pojo.GuserInfo;
import com.szsky.sky.pojo.OaInSpurUser;
import com.szsky.sky.service.BasicPersonnelInformationService;
import com.szsky.sky.service.mq.AsyncMessageService;
import com.szsky.sky.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 齐行
 * @version 1.0
 * @description: TODO
 * @date 2025/6/18 10:06
 */
@Slf4j
@Service
public class BasicPersonnelInformationServiceImpl implements BasicPersonnelInformationService {

    @Resource
    private OaInspurOrganizeMapper oaInspurOrganizeMapper;

    @Resource
    private GorganizeMapper gorganizeMapper;

    @Resource
    private UmcPersonMapper umcPersonMapper;
    @Resource
    private UmcUserMapper umcUserMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserDeptMapper userDeptMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private MUserMapper mUserMapper;
    @Resource
    private AppMUserMapper appMUserMapper;

    @Resource
    private GuserInfoMapper guserInfoMapper;

    @Resource
    private OaInSpurUserMapper oaInSpurUserMapper;

    @Resource
    private AttendanceStatisticsMapper attendanceStatisticsMapper;

    @Resource
    private AsyncMessageService asyncMessageService;

    @Resource
    private UmcCharOrganMapper umcCharOrganMapper;

    @Resource
    private UmcOrganMapper umcOrganMapper;

    @Resource
    private GorgUserMapper gorgUserMapper;

    @Override
    public Result<Integer> changeDepartment(BasicPersonnelInformationDto basicPersonnelInformationDto) {

        if (Objects.nonNull(basicPersonnelInformationDto)) {

            UmcPerson umcPerson = umcPersonMapper.getUcUidByUserId(basicPersonnelInformationDto.getUserId());
            log.info("用户信息：{}", JSONObject.toJSONString(umcPerson));


            // 查询app端部门信息  3层

            QueryWrapper<Department> queryAppDeptWrapper = new QueryWrapper<>();
            queryAppDeptWrapper.eq("oid", basicPersonnelInformationDto.getDepartmentId());

            Department appDeptInfo = departmentMapper.selectOne(queryAppDeptWrapper);

            log.info("app端部门信息：{}", JSONObject.toJSONString(appDeptInfo));


            // 查询app端部门信息 2层
            QueryWrapper<Department> queryAppUnitWrapper = new QueryWrapper<>();
            queryAppUnitWrapper.eq("id", appDeptInfo.getParentId());

            Department appUnitInfo = departmentMapper.selectOne(queryAppUnitWrapper);

            log.info("app端单位信息：{}", JSONObject.toJSONString(appUnitInfo));


            // 一层
            Integer parentId = appUnitInfo.getParentId();


            // 查询用户信息
            QueryWrapper<User> queryUserWrapper = new QueryWrapper<>();
            queryUserWrapper.eq("uid", umcPerson.getUcUid());

            User user = userMapper.selectOne(queryUserWrapper);
            log.info("app用户信息：{}", JSONObject.toJSONString(user));

            QueryWrapper<UserDept> queryUserDeptWrapper = new QueryWrapper<>();
            queryUserDeptWrapper.eq("user_id", user.getId());
            queryUserDeptWrapper.eq("is_master", 1);

            UserDept userDept = userDeptMapper.selectOne(queryUserDeptWrapper);


            StringJoiner joiner = new StringJoiner(",");
            joiner.add("p1p");
            joiner.add("p" + parentId + "p");
            joiner.add("p" + appUnitInfo.getId() + "p");
            joiner.add("p" + appDeptInfo.getId() + "p");


            log.info("user_id:{}---dept_id:{}----user_path:{}", userDept.getId(), appDeptInfo.getId(), joiner.toString());

            LambdaUpdateWrapper<UserDept> updateUserDeptWrapper = new LambdaUpdateWrapper<>();
            updateUserDeptWrapper.set(appDeptInfo.getId() != null, UserDept::getDeptId, appDeptInfo.getId());
            updateUserDeptWrapper.set(StringUtils.isNoneBlank(joiner.toString()), UserDept::getUserPath, joiner.toString());
            updateUserDeptWrapper.eq(UserDept::getId, userDept.getId());
            int update = userDeptMapper.update(updateUserDeptWrapper);
            log.info("修改的条数：{}，使用id：{}", update, userDept.getId());

            if (StringUtils.isNotBlank(basicPersonnelInformationDto.getEmail())) {
                changeEmail(basicPersonnelInformationDto);
            }

            return Result.success(update);
        }


        return Result.error("修改信息为空！");
    }

    private void changeEmail(BasicPersonnelInformationDto dto) {
//        Employee employee = employeeMapper.selectById(dto.getUserId());
//        String idCardNum = employee.getIdCardNum();
//        LambdaQueryWrapper<UmcPerson> lam = new LambdaQueryWrapper<>();
//        lam.eq(UmcPerson::getCertNum, employee.getIdCardNum());
//        List<UmcPerson> umcPersonList = umcPersonMapper.selectList(lam);
        LambdaQueryWrapper<UmcUsers> lamUser = new LambdaQueryWrapper<>();
        lamUser.eq(UmcUsers::getUserId, dto.getUserId());
        lamUser.eq(UmcUsers::getStatus, 11);
        List<UmcUsers> umcUsersList = umcUserMapper.selectList(lamUser);
        if (CollectionUtil.isNotEmpty(umcUsersList)) {
            String ucUid = umcUsersList.get(0).getUcUid();
            LambdaUpdateWrapper<AppMUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(AppMUser::getEmail, dto.getEmail());
            updateWrapper.eq(AppMUser::getUserId, ucUid);
            appMUserMapper.update(updateWrapper);
        }
    }

    @Override
    public Result<Boolean> checkMobileOrEmail(String mobile, String email) {

        List<String> userTypes = Arrays.asList("2", "4", "6");
        List<String> userStat = Arrays.asList("1", "14", "15", "16", "17", "18", "2", "21", "3", "6", "7");

        if (StringUtils.isNoneBlank(mobile)) {

            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("MOB_PHON", mobile);
            Employee employee = employeeMapper.selectOne(queryWrapper);

            UmcPerson umcPerson = umcPersonMapper.checkMobile(mobile);

            QueryWrapper<MUser> mUserWrapper = new QueryWrapper<>();
            mUserWrapper.eq("mobile", mobile);

            MUser mUser = mUserMapper.selectOne(mUserWrapper);

            if (Objects.nonNull(employee) || Objects.nonNull(umcPerson) || Objects.nonNull(mUser)) {
                return Result.success(true);
            }


        } else if (StringUtils.isNoneBlank(email)) {

            QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("ID_CARD_NUM",umcPerson.getCertNum());
            queryWrapper.eq("EMAIL", email);
            Employee employee = employeeMapper.selectOne(queryWrapper);

            UmcPerson umcPerson = umcPersonMapper.checkEmail(email);

            QueryWrapper<MUser> mUserWrapper = new QueryWrapper<>();
            mUserWrapper.eq("email", email);

            MUser mUser = mUserMapper.selectOne(mUserWrapper);

            if (Objects.nonNull(employee) || Objects.nonNull(umcPerson) || Objects.nonNull(mUser)) {
                return Result.success(true);
            }

        }
        return Result.success(false);
    }

    @Override
    public Result<List<AttendanceStatisticsDto>> attendanceStatistics(AttendanceStatisticsQuery query) {
        if (StringUtils.isNotBlank(query.getSignTimeStart()) && StringUtils.isNotBlank(query.getSignTimeEnd())) {
            query.setSignTimeStart(DateUtil.format(DateUtil.beginOfDay(DateUtil.parse(query.getSignTimeStart())), "yyyy-MM-dd HH:mm:ss"));
            query.setSignTimeEnd(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(query.getSignTimeEnd())), "yyyy-MM-dd HH:mm:ss"));

            if (Objects.nonNull(query.getPage()) && Objects.nonNull(query.getSize())) {
                Page<AttendanceStatisticsDto> page = new Page<>();
                page.setCurrent(query.getPage());
                page.setSize(query.getSize());

                Long total = attendanceStatisticsMapper.attendanceStatisticsCount(query);

                List<String> attendanceStatisticsUcUids = attendanceStatisticsMapper.getAttendanceStatisticsUcUids(page, query);
                query.setUcUids(attendanceStatisticsUcUids);

                List<AttendanceStatisticsDto> attendanceStatisticsDtos = attendanceStatisticsMapper.attendanceStatistics(query);
                log.info("考勤统计分页信息：{}", JSONObject.toJSONString(attendanceStatisticsDtos));
                Result<List<AttendanceStatisticsDto>> result = Result.success();
                result.setData(attendanceStatisticsDtos);
                result.setTotal(total);
                return result;
            } else {
                return Result.error("分页参数信息为空，请传入相关得分页参数");
            }
        } else {
            return Result.error("日期查询条件为空");
        }
    }

    @Override
    public Result<Boolean> synchronousZeroTrust(List<String> ids) {
        List<ToZeroProducerDto> toZeroProducerDtos = new ArrayList<>();
        // 同步勾选得人员
        List<Employee> employees;
        try {
            if (CollectionUtil.isEmpty(ids)) {
//                employees = employeeMapper.selectList(null);
                return Result.error("请选择要同步的人员");
            } else {
                QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
                employeeQueryWrapper.in("id", ids);
                //1. 查询人员基本信息
                employees = employeeMapper.selectList(employeeQueryWrapper);
            }

            log.info("人员信息：{}", JSONObject.toJSONString(employees));

            if (CollectionUtil.isNotEmpty(employees)) {
                Map<String, Employee> employeeMap = employees.stream().collect(Collectors.toMap(Employee::getIdCardNum, item -> item, (key1, key2) -> key1));

                //2. 将人员基本信息集合转换为身份证号集合

                List<String> idCarNumList = employees.stream().map(Employee::getIdCardNum).collect(Collectors.toList());

                //3. 使用身份证号查询 g_user_info信息
                LambdaQueryWrapper<GuserInfo> guserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                guserInfoLambdaQueryWrapper.in(GuserInfo::getIdNumber, idCarNumList);
                List<GuserInfo> guserInfos = guserInfoMapper.selectList(guserInfoLambdaQueryWrapper);

                // 4. 获取g_user_info信息中的id
                List<String> gUserInfoIdList = guserInfos.stream().map(GuserInfo::getId).collect(Collectors.toList());

                // 5. 使用g_user_info信息中的id查询 oa_inpur_user 信息

                LambdaQueryWrapper<OaInSpurUser> oaInSpurUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                oaInSpurUserLambdaQueryWrapper.in(OaInSpurUser::getOaUserId, gUserInfoIdList);

                List<OaInSpurUser> oaInSpurUsers = oaInSpurUserMapper.selectList(oaInSpurUserLambdaQueryWrapper);

                // 6. 获取uc_uid
                List<String> ucUidList = oaInSpurUsers.stream().map(OaInSpurUser::getInspurId).collect(Collectors.toList());


                List<UmcPerson> umcPersonList = umcPersonMapper.getUmcPersonByUcUid(ucUidList);

                List<String> organIdList = employees.stream().map(Employee::getDepartmentId).collect(Collectors.toList());

                LambdaQueryWrapper<UmcCharOrgan> charOrganLambdaQueryWrapper = new LambdaQueryWrapper<>();
                charOrganLambdaQueryWrapper.in(UmcCharOrgan::getOrganId, organIdList);
                List<UmcCharOrgan> umcCharOrganList = umcCharOrganMapper.selectList(charOrganLambdaQueryWrapper);

                Map<String, UmcCharOrgan> umcCharOrganMap = umcCharOrganList.stream().collect(Collectors.toMap(UmcCharOrgan::getOrganId, item -> item, (key1, key2) -> key1));

                LambdaQueryWrapper<UmcOrgan> umcOrganLambdaQueryWrapper = new LambdaQueryWrapper<>();
                umcOrganLambdaQueryWrapper.in(UmcOrgan::getOrganId, organIdList);
                List<UmcOrgan> umcOrganList = umcOrganMapper.selectList(umcOrganLambdaQueryWrapper);

                Map<String, UmcOrgan> umcOrganMap = umcOrganList.stream().collect(Collectors.toMap(UmcOrgan::getOrganId, item -> item, (key1, key2) -> key1));

                for (UmcPerson umcPerson : umcPersonList) {
                    ToZeroProducerDto toZeroProducerDto = new ToZeroProducerDto();

                    toZeroProducerDto.setOper("U");
                    toZeroProducerDto.setUcUid(umcPerson.getUcUid());
                    toZeroProducerDto.setUserId(umcPerson.getUserId());
                    toZeroProducerDto.setUserName(umcPerson.getUName());
                    toZeroProducerDto.setSex(umcPerson.getSex());
                    toZeroProducerDto.setAccoutStatus(umcPerson.getStatus());
                    toZeroProducerDto.setAuthLevel(umcPerson.getAuthenLevel());
                    toZeroProducerDto.setCertNum(umcPerson.getCertNum());
                    toZeroProducerDto.setPhone(umcPerson.getPhone());
                    toZeroProducerDto.setEmail(umcPerson.getEmail());
                    toZeroProducerDto.setBirthdate(umcPerson.getBirthdate() == null ? "" : umcPerson.getBirthdate());
                    toZeroProducerDto.setOfficePhone(umcPerson.getOfficePhone() == null ? "" : umcPerson.getOfficePhone());

                    List<Character> characters = new ArrayList<>();

                    Character character = new Character();
                    character.setOper(toZeroProducerDto.getOper());
                    Employee employee = employeeMap.get(umcPerson.getCertNum());
                    if (StringUtils.isNotBlank(employee.getDepartmentId())) {
                        character.setChartId(umcCharOrganMap.get(employee.getDepartmentId()).getCharId());
                        character.setCharId(umcCharOrganMap.get(employee.getDepartmentId()).getCharId());
                        if (StringUtils.isNotBlank(employee.getTechPosCode())) {
                            character.setChartName(employee.getTechPosCode());
                            character.setCharName(employee.getTechPosCode());
                        } else if (StringUtils.isNotBlank(employee.getJobTitleCode())) {
                            character.setChartName(employee.getJobTitleCode());
                            character.setCharName(employee.getJobTitleCode());
                        } else {
                            character.setChartName("员工");
                            character.setCharName("员工");
                        }
                        character.setOrganId(employee.getDepartmentId());
                        // TODO roles 待确定
                        character.setRoles("");
                        character.setSortNo(umcCharOrganMap.get(employee.getDepartmentId()).getSortNo());
                        character.setBdefault(Boolean.TRUE);
                        character.setOrganName(umcOrganMap.get(employee.getDepartmentId()).getOrganName());
                        character.setOrganType(umcOrganMap.get(employee.getDepartmentId()).getOrganType());

                    }

                    characters.add(character);
                    toZeroProducerDto.setCharacters(characters);
                    // 插入集合
                    toZeroProducerDtos.add(toZeroProducerDto);
                }


                // 2. 异步启动消息发送任务，不阻塞当前请求
                asyncMessageService.startAsyncSending(toZeroProducerDtos);


                Result<Boolean> result = Result.success();
                result.setData(true);
                result.setMessage("处理成功，正在后台处理中...");
                // 3. 立即返回结果
                return result;
            }
            return Result.success();
        } catch (Exception e) {
            log.error("处理同步请求失败", e);
            return Result.error("处理请求失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> cancelSecondment(List<BasicPersonnelInformationDto> dtoList) {

        List<String> ids = dtoList.stream().map(BasicPersonnelInformationDto::getId).collect(Collectors.toList());

        try {
            if (CollectionUtil.isEmpty(ids)) {
                return null;
            }
            LambdaQueryWrapper<Employee> lam = new LambdaQueryWrapper<>();
            lam.in(Employee::getId, ids);
            List<Employee> employeeList = employeeMapper.selectList(lam);
            if (CollectionUtil.isEmpty(employeeList)) {
                return null;
            }
            List<String> idcardNumList = employeeList.stream().map(Employee::getIdCardNum).collect(Collectors.toList());
            LambdaQueryWrapper<UmcPerson> umcPersonLam = new LambdaQueryWrapper<>();
            umcPersonLam.select(UmcPerson::getUcUid, UmcPerson::getUName, UmcPerson::getSex,  UmcPerson::getCertNum, UmcPerson::getPhone, UmcPerson::getEmail, UmcPerson::getOfficePhone);
            umcPersonLam.in(UmcPerson::getCertNum, idcardNumList);
            List<UmcPerson> umcPersonList = umcPersonMapper.selectList(umcPersonLam);
            List<String> ucUidList = umcPersonList.stream().map(UmcPerson::getUcUid).collect(Collectors.toList());

            LambdaQueryWrapper<User> userLam = new LambdaQueryWrapper<>();
            userLam.in(User::getUId, ucUidList);
            List<User> userList = userMapper.selectList(userLam);

            List<Integer> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());


            QueryWrapper<Department> queryDep = new QueryWrapper<>();
//            queryDep.select("id","name");
            queryDep.eq("oid",dtoList.get(0).getDepartmentId());
            Department department = departmentMapper.selectOne(queryDep);

            LambdaUpdateWrapper<UserDept> userDeptLam = new LambdaUpdateWrapper<>();
            userDeptLam.eq(UserDept::getUserId, userIdList.get(0));
            userDeptLam.eq(UserDept::getDeptId, department.getId());
            userDeptMapper.delete(userDeptLam);

            LambdaQueryWrapper<Department> depLam = new LambdaQueryWrapper<>();
            for (Employee employee : employeeList) {
                depLam = new LambdaQueryWrapper<>();
                depLam.eq(Department::getOid, employee.getDepartmentId());
                List<Department> depList = departmentMapper.selectList(depLam);
                Integer depId = depList.get(0).getId();
                User user = userList.stream().findFirst().get();


                userDeptLam = new LambdaUpdateWrapper<>();
                userDeptLam.eq(UserDept::getUserId, user.getId());
                userDeptLam.eq(UserDept::getDeptId, depId);
                userDeptLam.set(UserDept::getIsMaster, 1);
                userDeptMapper.update(userDeptLam);
            }

            // 取消oa挂职数据
            String idcardNum = idcardNumList.get(0);
            LambdaQueryWrapper<GuserInfo> guserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            guserInfoLambdaQueryWrapper.eq(GuserInfo::getIdNumber,idcardNum);
            GuserInfo guserInfo = guserInfoMapper.selectOne(guserInfoLambdaQueryWrapper);

            LambdaQueryWrapper<Gorganize> cancelSecondmentWrapper = new LambdaQueryWrapper<>();
            cancelSecondmentWrapper.eq(Gorganize::getRemark,dtoList.get(0).getDepartmentId());
            Gorganize gorganize = gorganizeMapper.selectOne(cancelSecondmentWrapper);

            LambdaQueryWrapper<Gorganize> oldDeptWrapper = new LambdaQueryWrapper<>();
            oldDeptWrapper.eq(Gorganize::getRemark,employeeList.get(0).getDepartmentId());

            Gorganize gorganizeOld = gorganizeMapper.selectOne(oldDeptWrapper);

            LambdaQueryWrapper<GorgUser> delCancelSecondmentWrapper = new LambdaQueryWrapper<>();
            delCancelSecondmentWrapper.eq(GorgUser::getUserId,guserInfo.getId());
            delCancelSecondmentWrapper.eq(GorgUser::getOrgId,gorganize.getId());
            int delete = gorgUserMapper.delete(delCancelSecondmentWrapper);

            if (delete > 0){
                log.info("ID为：{}，数据已删除",gorganize.getId());

                // 恢复默认部门为主部门

                LambdaUpdateWrapper<GorgUser> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(GorgUser::getUserId,guserInfo.getId());
                updateWrapper.eq(GorgUser::getOrgId,gorganizeOld.getId());
                updateWrapper.set(GorgUser::getIsMain,new BigDecimal("1"));
                updateWrapper.set(GorgUser::getIsMainText,"是");

                int update = gorgUserMapper.update(updateWrapper);
                if (update > 0){
                    log.info("userID:{},orgId:{} - 数据已经修改",guserInfo.getId(),gorganizeOld.getId());
                }
            }


            Result<Boolean> result = Result.success();
            result.setData(true);
            result.setMessage("处理成功");
            // 3. 立即返回结果
            return result;
        } catch (Exception e) {
            log.error("取消挂职请求失败", e);
            return Result.error("取消挂职请求失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> addSecondment(List<BasicPersonnelInformationDto> list) {
        try {
            if (CollectionUtil.isNotEmpty(list)) {
                List<String> idList = list.stream().map(BasicPersonnelInformationDto::getId).collect(Collectors.toList());
                LambdaQueryWrapper<Employee> lam = new LambdaQueryWrapper<>();
                lam.in(Employee::getId, idList);
                List<Employee> employeeList = employeeMapper.selectList(lam);

                Map<String, BasicPersonnelInformationDto> dtoMap = list.stream().collect(Collectors.toMap(BasicPersonnelInformationDto::getId, item -> item, (k1, k2) -> k1));

                if (CollectionUtil.isNotEmpty(employeeList)) {
                    LambdaQueryWrapper<Department> depLam = new LambdaQueryWrapper<>();
                    LambdaQueryWrapper<User> userLam = new LambdaQueryWrapper<>();
                    LambdaUpdateWrapper<UserDept> userDeptLam = new LambdaUpdateWrapper<>();
                    UserDept userDept = new UserDept();
                    for (Employee employee : employeeList) {
                        UmcPerson umcPerson = umcPersonMapper.getUcUidByCertNum(employee.getIdCardNum());

                        userLam = new LambdaQueryWrapper<>();
                        userLam.eq(User::getUId, umcPerson.getUcUid());
                        User user = userMapper.selectOne(userLam);
                        Integer userId = user.getId();

                        depLam = new LambdaQueryWrapper<>();
                        depLam.eq(Department::getOid, dtoMap.get(employee.getId()).getDepartmentId());
                        List<Department> depList = departmentMapper.selectList(depLam);
                        String path = null;
                        Integer depId = null;
                        if (CollectionUtil.isNotEmpty(depList)) {
                            depId = depList.get(0).getId();
                            path = depList.get(0).getPath() + ",p" + depId + "p";
                        }

                        if (StringUtils.isNotBlank(employee.getIdCardNum())){

                            // 查询oa部门信息
                            LambdaQueryWrapper<Gorganize>  gorganizeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            gorganizeLambdaQueryWrapper.eq(Gorganize::getRemark, dtoMap.get(employee.getId()).getDepartmentId());
                            Gorganize gorganize = gorganizeMapper.selectOne(gorganizeLambdaQueryWrapper);


                            //人员身份证号信息
                            String idCardNum = employee.getIdCardNum();
                            //根据身份证号查询用户基本信息
                            LambdaQueryWrapper<GuserInfo> guserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            guserInfoLambdaQueryWrapper.eq(GuserInfo::getIdNumber, idCardNum);
                            GuserInfo guserInfo = guserInfoMapper.selectOne(guserInfoLambdaQueryWrapper);


                            //组装oa部门信息保存

                            GorgUser gorgUser = getGorgUserObj(gorganize,guserInfo);

                            // 保存挂职部门信息
                            int insert = gorgUserMapper.insert(gorgUser);
                            if (insert > 0){
                                log.info("添加人员挂职，oa数据信息保存成功，ID：{}",guserInfo.getId());

                                String departmentId = employee.getDepartmentId();
                                LambdaQueryWrapper<Gorganize> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                                lambdaQueryWrapper.eq(Gorganize::getRemark, departmentId);
                                Gorganize selectedOneGorganize = gorganizeMapper.selectOne(lambdaQueryWrapper);


                                LambdaQueryWrapper<GorgUser> gorgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                gorgUserLambdaQueryWrapper.eq(GorgUser::getUserId,guserInfo.getId());
                                gorgUserLambdaQueryWrapper.eq(GorgUser::getOrgId,selectedOneGorganize.getId());
                                GorgUser selectOne = gorgUserMapper.selectOne(gorgUserLambdaQueryWrapper);

                                LambdaUpdateWrapper<GorgUser> updateWrapper = new LambdaUpdateWrapper<>();
                                updateWrapper.eq(GorgUser::getId,selectOne.getId());
                                updateWrapper.set(GorgUser::getIsMain,new BigDecimal("0"));
                                updateWrapper.set(GorgUser::getIsMainText,"否");

                                int update = gorgUserMapper.update(updateWrapper);
                                if (update > 0){
                                    log.info("ID为：{}，数据修改成功！",selectOne.getId());
                                }
                            }

                        }

                        if (userId != null && depId != null && StringUtils.isNotBlank(path)) {
                            userDeptLam = new LambdaUpdateWrapper<>();
                            userDeptLam.eq(UserDept::getUserId, userId);
                            userDeptLam.set(UserDept::getIsMaster, 0);
                            userDeptMapper.update(userDeptLam);
                            userDept.setUserId(userId);
                            userDept.setDeptId(depId);
                            userDept.setIsMaster(1);
                            userDept.setOfficeName(employee.getTechPosCode());
                            userDept.setUserPath(path);
                            userDeptMapper.insert(userDept);

                            Result<Boolean> result = Result.success();
                            result.setData(true);
                            result.setMessage("处理成功，正在后台处理中...");
                            // 3. 立即返回结果
                            return result;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("添加撷取请求失败", e);
            return Result.error("添加撷取请求失败：" + e.getMessage());
        }
        return null;
    }

    private GorgUser getGorgUserObj(Gorganize gorganize, GuserInfo guserInfo) {
        GorgUser gorgUser = new GorgUser();
        gorgUser.setId(IdWorker.getIdStr());
        gorgUser.setUserId(guserInfo.getId());
        gorgUser.setOrgId(gorganize.getId());
        gorgUser.setIsMain(new BigDecimal("1"));
        gorgUser.setIsMainText("是");
        gorgUser.setShowOrder(new BigDecimal("0"));
        gorgUser.setProjectId(gorganize.getProjectId());
        gorgUser.setCreateUserId("2");
        gorgUser.setCreateUserName("系统管理员");
        gorgUser.setCreateDeptId("180505162656YILYYOzw1FnE5OzzNxm");
        gorgUser.setCreateDeptName("中国社会科学院");
        gorgUser.setCreateUnitId("180505162656YILYYOzw1FnE5OzzNxm");
        gorgUser.setCreateUnitName("中国社会科学院");
        gorgUser.setCreateTime(new DateTime());
        gorgUser.setLastUpdateUnitId("2");
        gorgUser.setLastUpdateUserName("系统管理员");
        gorgUser.setLastUpdateDeptId("180505162656YILYYOzw1FnE5OzzNxm");
        gorgUser.setLastUpdateDeptName("中国社会科学院");
        gorgUser.setLastUpdateUnitId("180505162656YILYYOzw1FnE5OzzNxm");
        gorgUser.setLastUpdateUnitName("中国社会科学院");
        gorgUser.setLastUpdateTime(new DateTime());
        gorgUser.setRowState(new BigDecimal("1"));
        gorgUser.setIsModify(new BigDecimal("-1"));
        gorgUser.setUnitId("180505162656YILYYOzw1FnE5OzzNxm");
        gorgUser.setStep(gorganize.getStep());
        gorgUser.setUserOrgId(""); //TODO 暂时不知道是什么
        gorgUser.setUnitRank(guserInfo.getUnitRankText());
        gorgUser.setRankCodeOrder(new BigDecimal("0"));

        return gorgUser;
    }
}
